package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import cn.wolfcode.rbac.query.EmployeeQueryObject;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void saveOrUpdate(Employee employee,Long[] roleIds) {
        if (employee.getId()!=null){
            // id不为空,说明此时调用的是修改操作
            // Update 表名 set name=?,sn=? where id=?;
            employeeMapper.updateByPrimaryKey(employee);

            employeeMapper.deleteEmployeeAndRoleRelation(employee.getId());
        }else {
            // id为空,说明此时调用的是保存操作
            // insert into 表名(name,sn) values(?,?)
            employeeMapper.insert(employee);
        }

        //添加新的employee_role关系,因为不管是新增/修改操作,都需要添加新关系 ,for each 的快捷键是  iter
        if (roleIds != null){
            for (Long roleId : roleIds) {
                employeeMapper.addEmployeeAndRoleRelation(employee.getId(),roleId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Employee getOne(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> listAll() {
        List<Employee> employees = employeeMapper.selectAll();
        return employees;
    }

    @Override
    public PageResult query(EmployeeQueryObject qo) {
        //查询总条数
        int totalCount = employeeMapper.queryForCount(qo);
        //查询带有分页效果的结果集
        if (totalCount == 0){
            //查不出数据,调用的是pageResult类中的缺参构造器
            return new PageResult(qo.getCurrentPage(),qo.getPageSize());
        }

        List<Employee> data = employeeMapper.queryForList(qo);
        return new PageResult(data,totalCount,qo.getCurrentPage(),qo.getPageSize());
    }

    @Override
    public void login(String username,String password){
        // 根据账号和密码上数据库去查询是否有数据
        Employee employee=employeeMapper.login(username, password);
        if(employee == null){
            throw new RuntimeException("账号或密码不正确");
        }

        // 把 employee 放到 session 中
        UserContext.setCurrent(employee);
        // 用户所拥有的权限表达式集合
        List<String> expressions= permissionMapper.selectPermissionByEmpId(employee.getId());
        // 把用户所拥有的权限放到session中
        UserContext.setExpressions(expressions);
    }
}
